package com.example.demo.controller;

import com.example.demo.config.SpringBootApplicationListener;
import com.example.demo.domain.Response;
import com.example.demo.service.Test2Service;
import com.example.demo.service.Test3Service;
import com.example.demo.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.Closeable;
import java.io.IOException;
import java.util.Map;

@RequestMapping("/test")
@RestController
@Slf4j
public class TestController {

    @GetMapping("/restartApp")
    public Response testRestart() {
        if (SpringBootApplicationListener.sa == null) {
            log.info("未获取到springbootapplication");
        } else {
            Thread thread = new Thread(() -> {
                SpringBootApplicationListener.sa.setEnvironment(SpringBootApplicationListener.context.getEnvironment());
                close();
                ClassUtils.overrideThreadContextClassLoader(SpringBootApplicationListener.sa.getClass().getClassLoader());
                SpringBootApplicationListener.sa.run(SpringBootApplicationListener.args);
            });
            thread.setDaemon(false);
            thread.start();
        }
        return Response.success();
    }

    private void close() {
        ApplicationContext context = SpringBootApplicationListener.context;
        while (context instanceof Closeable) {
            try {
                ((Closeable) context).close();
            } catch (IOException e) {
                log.error("Cannot close context: " + context.getId(), e);
            }
            context = context.getParent();
        }
    }

    @Resource
    TestService testService;

    /**
     * Spring中bean默认是单例的，打印的时间始终是一样的
     * @return
     */
    @GetMapping("/test1")
    public Map<String, String> test1() {
        return testService.service1();
    }

    /**
     * TestController是Spring的Bean，初始化TestController时会初始化它的成员属性Test2Service,使得初始话localDateTime
     * 所以打印时间也是一样的
     */
    Test2Service test2Service = new Test2Service();

    @GetMapping("/test2")
    public Map<String, String> test2() {
        return test2Service.service2();
    }

    /**
     * 打印时间始终不一样
     *
     * @return
     */
    @GetMapping("/test3")
    public Map<String, String> test3() {
        Test3Service test3Service = new Test3Service();
        return test3Service.service2();
    }

    Test3Service test3Service;

    @GetMapping("/test4")
    public Map<String, String> test4() {
        test3Service = new Test3Service();
        return test3Service.service2();
    }
}
